package com.gw.yunke.service.impl;

import com.gw.yunke.dao.CollectMapper;
import com.gw.yunke.dao.CourseMapper;
import com.gw.yunke.domain.Collect;
import com.gw.yunke.domain.CollectExample;
import com.gw.yunke.domain.Course;
import com.gw.yunke.domain.dto.CollectReq;
import com.gw.yunke.domain.dto.CollectResp;
import com.gw.yunke.service.ICollectService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class CollectServiceImpl implements ICollectService{

  @Autowired
  private CollectMapper collectMapper;
  @Autowired
  private CourseMapper courseMapper;

  @Override
  public int addCollect(Collect collect) {

    courseMapper.addLikeAmount(collect.getCourseId());

    return collectMapper.insert(collect);
  }

  @Override
  public List<CollectResp> getCollects(CollectReq collectReq) {
    CollectExample example = new CollectExample();
    CollectExample.Criteria criteria = example.createCriteria();
    if(collectReq.getCourseId() != null){
      criteria.andCourseIdEqualTo(collectReq.getCourseId());
    }
    if(!StringUtils.isEmpty(collectReq.getCourseCode())){
      criteria.andCourseCodeEqualTo(collectReq.getCourseCode());
    }
    criteria.andUserIdEqualTo(collectReq.getUserId());

    List<Collect> collectList = collectMapper.selectByExample(example);
    List<CollectResp> collectRespList = new ArrayList<>();
    for(Collect collect : collectList){
      CollectResp resp = new CollectResp();
      resp.setCourseId(collect.getCourseId());
      resp.setUserId(collect.getUserId());
      Course course = courseMapper.selectByPrimaryKey(collect.getCourseId());
      if(course!=null)
        resp.setCourseName(course.getName());

      collectRespList.add(resp);
    }
    return collectRespList;
  }

  @Override
  public int cancelCollect(Long courseId) {
    CollectExample example = new CollectExample();
    CollectExample.Criteria criteria = example.createCriteria();
    criteria.andCourseIdEqualTo(courseId);
    courseMapper.subLikeAmount(courseId);
    return collectMapper.deleteByExample(example);
  }
}
